/*
 * Copyright (c) 2020 - present, Inspur Genersoft Co., Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package io.iec.edp.caf.session.spring;

import org.springframework.boot.autoconfigure.session.SessionProperties;
import org.springframework.session.config.SessionRepositoryCustomizer;
import org.springframework.session.data.redis.RedisIndexedSessionRepository;

import java.time.Duration;

/**
 * spring SessionRepository(redis)的SessionRepositoryCustomizer，设置session超时时间和namespace
 *
 * @author wangyandong
 * @date 2020/07/22 17:26
 */
public class CafSpringSessionRepositoryCustomizer implements SessionRepositoryCustomizer<RedisIndexedSessionRepository> {

    //session在redis中命名空间
    private final static String NameSpace = "caf-session";

    //spring.session配置节
    private SessionProperties sessionProperties;

    public CafSpringSessionRepositoryCustomizer(SessionProperties sessionProperties) {
        this.sessionProperties = sessionProperties;
    }

    public void customize(RedisIndexedSessionRepository sessionRepository) {
        //设置session超时时间
        Duration timeout = sessionProperties.getTimeout();
        if (timeout != null) {
            sessionRepository.setDefaultMaxInactiveInterval((int) timeout.getSeconds());
        }

        //设置redis-session的命名空间
        sessionRepository.setRedisKeyNamespace(NameSpace);
    }
}
